package com.demo.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.demo.entity.Student;
import com.demo.service.IMGService;
import com.demo.service.IStudentService;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MgServiceImpl implements IMGService {



    @Resource
    private IStudentService studentService;

    private static MongoClient mongoClient=null;
    private static MongoDatabase database=null;
    private static MongoCollection<Document> collection=null;
    private static final int CONNECTION_PER_HOST = 1;
    private static final String REPLICASET_NAME = "mongodb";

    static {
        //1、创建MongoClient客户端对象
        mongoClient = MongoClients.create("mongodb://localhost:27017/");
        //2、得到数据库对象，aLongDatabase，则创建一个
        database = mongoClient.getDatabase("aLongDatabase");
        //3、访问集合，aLongCollection，则创建
        collection = database.getCollection("aLongCollection");
        new MongoClientOptions.Builder()
                .requiredReplicaSetName(REPLICASET_NAME)
                .maxConnectionIdleTime(0)
                .connectionsPerHost(CONNECTION_PER_HOST)
                .cursorFinalizerEnabled(false)
                .build();
    }

    @Override
    public int insertMGOne() {
        Document doc = new Document("name", "update")
                .append("name","u1")
                .append("phone","1");
        collection.insertOne(doc);
        Document append = new Document("name", "delete")
                .append("name", "d1")
                .append("phone", "2");
        collection.insertOne(append);
        mongoClient.close();
        return 1;
    }

    @Override
    public int insertStudent(Student student) {
        try {
            Document doc = new Document("name", "student")
                    .append("id" , student.getId())
                    .append("name" , student.getName())
                    .append("phone" , student.getPhone());
            collection.insertOne(doc);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }

    @Override
    public int insertManyData() {
        try {
            List<Student> students = studentService.selectAll();
            ArrayList<Document> documents = new ArrayList<>();
            for (int i = 0; i < students.size(); i++) {
                documents.add(new Document("name","student2")
                        .append("id",students.get(i).getId())
                        .append("name" , students.get(i).getName())
                        .append("phone",students.get(i).getPhone())
                );
            }
            collection.insertMany(documents);
        }catch (Exception e){
            return 0;
        }
        return 1;
    }

    @Override
    public Document selectOne() {
        Document first = collection.find().first();
        return first;
    }

    @Override
    public List selectAll() {
        TimeInterval timer = DateUtil.timer();
        ArrayList<Object> objects = new ArrayList<>();
        MongoCursor<Document> iterator = collection.find().iterator();
        try {
            try {
                while (iterator.hasNext()){
                    objects.add(iterator.next().toJson());
                }
            }finally {
                iterator.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        long interval = timer.interval();
        String s = "花费时间为："+interval + "毫秒" ;
        objects.add(s);
        return objects;
    }

    @Override
    public List<Object> selectByName(String s) {
        FindIterable<Document> name = collection.find(Filters.eq("name", s));
        List<Object> list = FindShow(name);
        return list;
    }

    @Override
    public int updateByName(String name , String phone) {
        try {
            collection.updateOne(Filters.eq("name" , name),
                    new Document("$set" , new Document("phone" , phone)));
            FindShow(collection.find());
        }catch (Exception e){
            System.err.println("修改失败");
            return 0;
        }
        return 1;
    }

    @Override
    public int deleteByName(String name) {
        try {
            collection.deleteMany(Filters.eq("name" , name));
            FindIterable<Document> documents = collection.find();
            FindShow(documents);
        }catch (Exception e){
            System.err.println("删除失败");
            return 0;
        }
        return 1;
    }

    @Override
    public int insertListStudent(List<Student> students) {
        ArrayList<Document> documents = new ArrayList<>();
        if (CollUtil.isEmpty(students)){
            System.err.println("数据已失效");
            return 0;
        }
        try {

            students.forEach(a ->
                    documents.add(new Document()
                            .append("id" , a.getId())
                            .append("name" , a.getName())
                            .append("phone" , a.getPhone())
                        )
                    );
            collection.insertMany(documents);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    private static List<Object> FindShow(FindIterable<Document> documents){
        ArrayList<Object> objects = new ArrayList<>();
        MongoCursor<Document> iterator = documents.iterator();
        try {
            while (iterator.hasNext()){
                objects.add(iterator.next().toJson());
            }
        }finally {
            iterator.close();
        }
        return objects;
    }

}
